<template>
    <div class="form-content view" ref="form" >
    </div>

</template>

<script>
    var annexes = {};
    var component = {
        props:["data","type"],
        // watch: {
        //     data: function(nv){
                // if(!nv){
                //     return
                // }
                // if(!Object.keys(nv).length){
                //     return;
                // }
            // }
        // },
        data: function () {
            return {}
        },
        mounted: function(){
            this.init()
        },
        methods: {
            init: function () {
                this.$refs.form.innerHTML = this.data.form;
                var t = this;
                var body = $(this.$refs.form);

                var fields = this.data.formFields|| [];
                // 不在填写字段中，必填中的字段默认为可填写字段
                $.each(this.data.requiredFields|| [], function (i, v) {
                    if("-1" == $.inArray(v,fields)){
                        fields.push(v);
                    }
                });

                //特殊字段处理
                body.find("[leipiplugins=chooseuser],[leipiplugins=choosedep]").each(function () {
                    var _this = $(this);
                    var attr = _this.attr('leipiplugins');
                    $("<span>")
                        .attr({
                            leipiplugins: attr,
                            title: _this.attr("title"),
                            name: _this.attr("name")
                        })
                        .css({
                            width: _this.attr("orgwidth"),
                            height: _this.attr("orgheight"),
                            "align-items": "flex-end",
                            display: "inline-flex"
                        })
                        .append(
                            $("<textarea>")
                                .attr({
                                    readonly: 1
                                })
                                .css({
                                    flex: 1,
                                    resize: "none",
                                    background: "#eee"
                                })
                        )
                        .insertAfter(this)
                        .append(this);
                    _this.removeAttr("leipiplugins");
                    _this.removeAttr("name");
                });

                //处理附件控件
                body.find("[leipiplugins=annex]").each(function () {
                    var _this = $(this);
                    var title = _this.attr("title");
                    var name = t.data.allFields[title].name;
                    var id = "annex-" + name;
                    var item = $("<div>")
                        .attr({
                            leipiplugins:"annex",
                            id: id,
                            name: name,
                            title: title
                        })
                        .css({
                            width: _this.attr("orgwidth"),
                            padding: 5,
                            "box-sizing":"border-box"
                        })
                        .append("<ins-annex ref='annex' :deal='deal' :files='files'></ins-annex>");
                    _this.replaceWith(item);
                    annexes[title] = new Vue({
                        el: "#" + id,
                        data:{
                            deal: false,
                            files: []
                        }
                    });
                });

                //全部设为disabled
                // body.find("input[leipiplugins]:not([type=radio]):not([type=checkbox]), textarea[leipiplugins]").val("").prop("disabled", "disabled");
                //只有宏字段和日期被设置为空, 其余需要保留默认值
                var elems = body.find("input[leipiplugins=macros], input[leipiplugins=datetime]")
                elems.val("");
                elems.attr('value', "")
                //设为disabled
                body.find("input,input[leipiplugins], textarea[leipiplugins], select[leipiplugins]").prop("disabled", "disabled");
                //select默认选第一个
                // body.find("select[leipiplugins]").each(function () {
                //     $(this).val($(this).find("option:first").val())
                // })

                //编辑模式
                if(t.type == 'edit'){
                    t.data.formFields = [];
                    for(var i in t.data.allFields){
                        t.data.formFields.push(i)
                    }
                }


                if(t.data.deal){
                    //当前节点可编辑
                    $.each(t.data.formFields || [], function (i, v) {
                        if(!t.data.allFields[v]){
                            return
                        }
                        console.log(t.data.allFields[v])
                        var elem = body.find("[name=" + t.data.allFields[v].name + "]");
                        elem.removeProp("disabled").css("border-color", "#06a4ff")
                        if(elem.is("[leipiplugins=datetime]")){
                            elem.prop("readonly","true")

                            ;(function (title, type) {
                                laydate.render({
                                    elem: "[leipiplugins=datetime][title="+title+"]"
                                    ,type: (function () {
                                        switch (type) {
                                            case "日期" :
                                                return "date";

                                            case "日期+时间":
                                                return "datetime";

                                            case "时间":
                                                return "time";
                                        }
                                    })(),
                                    done: function () {
                                        recal();
                                    }
                                })
                            })(elem[0].title, elem.attr("orgformat"));
                        }

                        if(elem.is("[leipiplugins=sign]")){
                            elem.click(function () {
                                var id = $(this).attr("name");
                                var src = $(this).attr("src");
                                window.open("./sign.html?name=" + id + "&src=" + src, "bpm-sign", "left=100, top=100, width=500, height=500, location=no")
                            });
                        }

                        if(elem.is("[leipiplugins=chooseuser],[leipiplugins=choosedep]")){
                            elem.find("img").click(function () {
                                window.onChooseInit = function(){
                                    return elem.data("data") || {};
                                };
                                window.onChooseCallback = function(selected){
                                    elem.data("data", selected)
                                    var val = Object.values(selected).join(",");
                                    elem.find("textarea")
                                        .val(val)
                                        .attr("value", val);
                                }
                                switch (elem.attr('leipiplugins')) {
                                    case "chooseuser":
                                        window.open("../org/choose.html", "choose-user", "left=100, top=100, width=500, height=500, location=no")
                                        break

                                    case "choosedep":
                                        window.open("../org/choose-dep.html", "choose-user", "left=100, top=100, width=500, height=500, location=no")
                                        break
                                }
                            }) ;
                        }

                        if(elem.is("[leipiplugins=chooseimage]")){
                            elem.click(function () {
                                $("<input type='file'>")
                                    .change(function () {
                                        var file = this.files[0];
                                        if(file.type.indexOf("image") == -1){
                                            return layer.msg("请选择正确的图片");
                                        }
                                        var reader = new FileReader();
                                        reader.readAsDataURL(file);
                                        reader.onload = function (e) {
                                            var image = e.target.result;
                                            var index = layer.load(2);
                                            $.ajax({
                                                url: "/api/bpm/workflow/uploadImage",
                                                type:"post",
                                                dataType:"json",
                                                headers:{
                                                    "Content-Type": "application/json"
                                                },
                                                data:JSON.stringify({base64: "data:" + image}),
                                                complete: function(){
                                                    layer.close(index);
                                                },
                                                success: function (msg) {
                                                    if(!msg.success){
                                                        layer.msg(msg.errMessage);
                                                    }
                                                    elem.attr("src", "/api/bpm/workflow/download?path=" + msg.data)
                                                },
                                            });
                                        }
                                    })
                                    .css("display", "none")
                                    .appendTo("body")
                                    .click()
                            });
                        }


                        if(elem.is("[leipiplugins=annex]")){
                            var title = t.data.allFields[v].title;
                            console.log(title, annexes[title].$refs)
                            annexes[title].deal = true;
                        }
                    });

                    //必填字段标红
                    $.each(t.data.requiredFields || [], function (i, v) {
                        body.find("[name=" + t.data.allFields[v].name + "]").removeProp("disabled").css("border-color", "#faa")
                    }) ;
                }

                //select默认值
                body.find("span[leipiplugins=select] select").each(function () {
                    var name = $(this).attr("name");
                    if(t.data.allFields[name]){
                        $(this).val(t.data.allFields[name].defaultValue)
                        $(this).attr("value", t.data.allFields[name].defaultValue)
                    }
                });

                //计算控件


                //时间字段
                var timer = null;
                function recal() {
                    if(timer){
                        clearTimeout(timer);
                        timer = null;
                    }
                    timer = setTimeout(function () {
                        timer = null;
                        //重新求计算控件的值
                        body.find("input[leipiplugins=macros]").each(function () {
                            var expression = $.trim($(this).attr('expression'));
                            if(!expression){
                                return
                            }
                            if($(this).is("[disabled]")){
                                return;
                            }
                            //需要求值
                            $(this).val(calculate_macro(expression))
                        });
                    });
                }

                body.on("input", "input[leipiplugins],textarea[leipiplugins]", function () {
                    recal();
                });

                //隐藏控件
                body.find("[leipiplugins][orghide=1]").hide();

                //字段赋值
                $.each(t.data.attrs || {}, function (i, v) {
                    var field = t.data.allFields[i];
                    if (!field) return
                    var tt = body.find("[name=" + field.name + "]")
                    if (field.leipiplugins == 'macros') {
                        tt.prop("readonly", "true")
                    }

                    if(tt.is("[leipiplugins=sign]")){
                        if(v){
                            var matched = v.match(/^\[img\](.+)$/);
                            if(matched){
                                tt.attr('src', matched[1])
                            }
                        }
                    }  else if(tt.is("[leipiplugins=chooseuser],[leipiplugins=choosedep]")){
                        if(v){
                            var matched = v.match(/^\[json\](.+)$/);
                            if(matched){
                                var d = JSON.parse(matched[1]);
                                var v = Object.values(d).join(",");
                                console.log(v)
                                tt.data("data", d);
                                tt.find("textarea")
                                    .val(v)
                                    .attr("value", v);

                                //打印页面赋值
                                tt.find("textarea")
                                    .html(v)
                                    .attr("value", v);
                            }
                        }

                    } else if(field.leipiplugins == 'select'){
                        if(v){
                            tt.val(v)
                            tt.attr("value", v)
                        }
                    } else if(field.leipiplugins =='chooseimage'){
                        if(v){
                            var matched = v.match(/^\[img\](.+)$/);
                            if(matched){
                                tt.attr('src', matched[1])
                            }
                        }
                    } else if(field.leipiplugins == 'annex'){
                        if(v){
                            var matched = v.match(/^\[annex\](.+)$/);
                            if(matched){
                                var json = JSON.parse(matched[1]);
                                annexes[field.title].files = json;
                            }
                        }

                    } else if(field.leipiplugins == 'textarea'){
                        if(v){
                            tt.val(v)
                            tt.attr("value", v)
                            //打印页面赋值
                            tt.html(v)
                        }
                    } else if(field.leipiplugins =='checkboxs'){
                        // tt.val(v)
                        // tt.attr("value", v)
                        if(v){
                            $.each(v.split(","),function(i,item){
                                if(!item){
                                    return
                                }
                                $("input[name="+field.name+"][value="+item+"]").attr("checked",true);
                            });
                        }

                    }else if(field.leipiplugins =='radios'){
                        if(v){
                            $("input[name="+field.name+"][value="+v+"]").attr("checked",true);
                        }

                    }else {
                        tt.val(v)
                        tt.attr("value", v)
                    }

                });


                    $.each(t.data.allFields || {}, function (i, v) {
                        var elem = body.find("[name=" + v.name + "]");
                        if (v.leipiplugins == 'comment') {
                            // 设有批注权限的角色可以填写批注
                            // elem.removeProp("disabled")
                            elem.click(function () {
                                $("#content").val("")
                                if(t.data.comment){
                                    layer.open({
                                        type: 1,
                                        //skin: 'layui-layer-rim', //加上边框
                                        area: ['400px', '230px'], //宽高
                                        content: $("#comment-model"),
                                        title:"填写批注"
                                    });
                                }else{
                                    layer.msg("您没有填写批注的权限")
                                }
                            });
                            return false;
                        }
                    })
            },

            getData: function () {
                var body = $(this.$refs.form);
                var t = this;
                var data = {}

                $.each(this.data.formFields|| [], function (i, v) {
                    var key = v;
                    if (!t.data.allFields[v]) {
                        return
                    }
                    var elem = body.find("[name=" + t.data.allFields[v].name + "]");
                    var val;
                    if (elem.is("[leipiplugins=sign]")) {
                        val = elem.attr("src");
                        if (val.indexOf("sign.png") > -1) {
                            val = "";
                        } else {
                            val = "[img]" + val;
                        }
                    }  else if(elem.is("[leipiplugins=chooseuser],[leipiplugins=choosedep]")){
                        val = "[json]" + (JSON.stringify(elem.data('data')) || "{}");
                    } else if(elem.is("[leipiplugins=chooseimage]")){
                        val = "[img]" + elem.attr('src');
                    } else if(elem.is("[leipiplugins=annex]")){
                        val = "[annex]" + JSON.stringify(annexes[elem.attr('title')].files.filter(function (e) {
                            return !e.hint
                        }));
                    } else if(elem.is("[type=checkbox]")){
                        val = "";
                        val = $('input:checkbox[name=' + t.data.allFields[v].name + ']:checked').map(function () {
                            return $(this).val();
                        }).get().join(",");
                    } else if(elem.is("[type=radio]")){
                        val = $("input[name=" + t.data.allFields[v].name +"]:checked").val();
                    }else {
                        val = elem.val();

                    }
                    data[key] = val;
                });
                return data;
            }
        }
    };
</script>

<style>
    .form-content *{
        outline: none;
    }
</style>